package com.zjsru.plan2025.oneday;

import java.util.HashMap;
import java.util.Map;

/**
 * 166. 分数到小数
 *
 * @Author: cookLee
 * @Date: 2025-09-24
 */
public class FractionToDecimal {

    public static void main(String[] args) {
        FractionToDecimal fractionToDecimal = new FractionToDecimal();
        System.out.println(fractionToDecimal.fractionToDecimal(4, 333));
    }

    /**
     * 模拟长除法
     *
     * @param numerator
     * @return {@link String}
     */
    public String fractionToDecimal(int numerator, int denominator) {
        long a = numerator;
        long b = denominator;
        //符号
        String sign = a * b < 0 ? "-" : "";
        a = Math.abs(a);
        b = Math.abs(b);

        //计算正数q 和 余数r
        long q = a / b;
        long r = a % b;
        if (r == 0) {
            return sign + q;
        }
        //构建前半部分
        StringBuilder sb = new StringBuilder(sign).append(q).append(".");
        Map<Long, Integer> map = new HashMap<>();
        map.put(r, sb.length());
        while (r > 0) {
            r *= 10;
            q = r / b;
            r = r % b;
            sb.append(q);
            //处理循环部分
            if (map.containsKey(r)) {
                int pos = map.get(r);
                return sb.substring(0, pos) + "(" + sb.substring(pos) + ")";
            }
            //记录余数对应位置
            map.put(r, sb.length());
        }
        return sb.toString();
    }
}
